#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <glad/glad.h>
#include <iostream>
#include "texture.h"

bool isPNG(const std::string &filename)
{
    int len = filename.size();
    if (len < 4) return false;
    std::string ext = filename.substr(len-4);
    return ext == ".png" || ext == ".PNG";
}

/* @implement */
unsigned int initTexture(unsigned int id, const char *filename) {
    unsigned int texture;
    glGenTextures(1, &texture);
    // call active texture before binding texture;
    // can be omitted if there's only one texture
    glActiveTexture(id);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    int width, height, channels;
    stbi_set_flip_vertically_on_load(true);
    unsigned char *data = stbi_load(filename, &width, &height, &channels, 0);
    if (data) {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0,
                isPNG(filename) ? GL_RGBA : GL_RGB,
                GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D); // 生成各尺寸的小纹理
    } else {
        std::cerr << "[err] Failed to load texture" << std::endl;
    }
    stbi_image_free(data);
    return texture;
}
